package com.example.testapplication

import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.testapplication.activity.RecyclerTestActivity
import com.example.testapplication.activity.TestActivity
import com.example.testapplication.base.BaseActivity
import com.example.testapplication.databinding.ActivityMainBinding
import com.example.testapplication.viewModel.MainViewModel
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
import java.util.*

class MainActivity : BaseActivity<ActivityMainBinding>() {
    private val TAG = "MainActivity"
    private val FLUTTER_ID = "engine_id"
    private lateinit var engine: FlutterEngine

    private val mainViewModel: MainViewModel by viewModels()

    override fun setLayout(): Int {
        return R.layout.activity_main
    }

    // 声明一个传感管理器对象
    private lateinit var mSensorMgr: SensorManager
    private var mStep = 0
    private var mStepCount = 0
    private val sensorEventListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent?) {
            if (event!!.sensor.type == Sensor.TYPE_STEP_DETECTOR) { //步行检测事件
                if (event.values[0] == 1.0f) {
                    mStep++
                }
            } else if (event.sensor.type == Sensor.TYPE_STEP_COUNTER) { //计步器事件

                for (i in 0 until event.values.size) {
                    Log.e(TAG, "--->" + event.values[i])
                }

                mStepCount = event.values[0].toInt()
            }
            val desc = "设备检测到您当前走了${mStep}步，总计数为${mStepCount}步"
            binding.setupTextView.text = desc
        }

        //当传感器精度改变时回调该方法，一般无需处理
        override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding?.viewModel = mainViewModel
        binding?.lifecycleOwner = this

        // 从系统服务中获取传感管理器对象
        mSensorMgr = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val sensorList = mSensorMgr.getSensorList(Sensor.TYPE_ALL)
        Log.i(TAG, "Sensor size:" + sensorList.size)
        for (i in 0 until sensorList.size) {
            val sensor = sensorList[i]
            //Pedometer 计步器
            Log.i(TAG, "Supported Sensor: " + sensor.name)
        }
        //检查传感器权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val ACTIVITY_RECOGNITION_PERMISSION = arrayOf(Manifest.permission.ACTIVITY_RECOGNITION)
            // 检查该权限是否已经获取
            val get = ContextCompat.checkSelfPermission(this, ACTIVITY_RECOGNITION_PERMISSION[0])
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (get != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求自动开启权限
                ActivityCompat.requestPermissions(this, ACTIVITY_RECOGNITION_PERMISSION, 321)
            }
        }

        //注册步行检测
        mSensorMgr.registerListener(
            sensorEventListener,
            mSensorMgr.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR),
            SensorManager.SENSOR_DELAY_NORMAL
        )
        //注册步行计数
        mSensorMgr.registerListener(
            sensorEventListener,
            mSensorMgr.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
            SensorManager.SENSOR_DELAY_NORMAL
        )

        //重置步数(注销总不是统计监听再重新注册)
        binding.rest.setOnClickListener {
            //注销
            mSensorMgr.unregisterListener(
                sensorEventListener,
                mSensorMgr.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
            )
            //注册
            mSensorMgr.registerListener(
                sensorEventListener,
                mSensorMgr.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                SensorManager.SENSOR_DELAY_NORMAL
            )
        }


//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            this.window.navigationBarColor = ContextCompat.getColor(this , R.color.purple_200)
//        }

//            //通过新引擎路由跳转到指定页面
//            startActivity(
//                FlutterActivity.withNewEngine()
//                    //增加路由条件(没有者直接跳转到main)
//                    .initialRoute("base")
//                    .build(this)
//            )
//            //通过已经创建的引擎跳转
//            FlutterEngineActivity.startForEngine(this, FLUTTER_ID)

        binding?.button?.setOnClickListener {
            mainViewModel.content.value = "xc789789"
            startActivity(Intent(this, TestActivity::class.java))
//            startActivity(Intent(this , TestDampingActivity::class.java))
//            clickTest(number++)
//            collectionTest()
        }

//        val timeUtils = TimeUtils()
        binding?.button2?.setOnClickListener {
//            timeUtils.start(1000)
//            bitmapTest()
            startActivity(Intent(this, RecyclerTestActivity::class.java))
        }
        initFlutterE()
    }

    private fun collectionTest() {
        val list = mutableListOf<CollectionTestModel>()
        list.add(CollectionTestModel(3, "我是三"))
        list.add(CollectionTestModel(5, "我是五"))
        list.add(CollectionTestModel(1, "我是一"))
        list.add(CollectionTestModel(4, "我是四"))
        list.add(CollectionTestModel(2, "我是八"))

//        //正序
//        Collections.sort(list, object : Comparator<CollectionTestModel> {
//            override fun compare(p0: CollectionTestModel, p1: CollectionTestModel): Int {
//                return if (p0.int > p1.int) {
//                    1
//                } else if (p0.int < p1.int) {
//                    -1
//                } else {
//                    0
//                }
//            }
//        })

//        //倒序
//        Collections.sort(list, object : Comparator<CollectionTestModel> {
//            override fun compare(p0: CollectionTestModel, p1: CollectionTestModel): Int {
//                return if (p0.int > p1.int) {
//                    -1
//                } else if (p0.int < p1.int) {
//                    1
//                } else {
//                    0
//                }
//            }
//        })

//        //翻转
//        Collections.reverse(list)

//        //随机排序
//        Collections.shuffle(list , Random(System.currentTimeMillis()))

        list.forEach {
            Log.e("collectionTest", "---->" + it.int)
        }
    }

    private data class CollectionTestModel(var int: Int, var content: String)

    private var dialog: AlertDialog? = null
    private var view: View? = null

    private var number = 0
    private var aNumber = arrayOfNulls<Int>(1)
    private fun clickTest(int: Int) {
        aNumber[0] = int
        Log.e("启动", "---${aNumber[0]}")
        if (dialog == null) {
            dialog = AlertDialog.Builder(this).create()
        }
        dialog?.show()

        if (view == null) {
            view = LayoutInflater.from(this).inflate(R.layout.dialog_view, null)
            dialog?.setContentView(view!!)
            view?.findViewById<TextView>(R.id.textView)?.setOnClickListener {
                Log.e("我就点了", "---${aNumber[0]}")
                dialog?.dismiss()
            }
        }

        val p = dialog?.window!!.attributes
        p.gravity = Gravity.BOTTOM
//        p.width = ViewGroup.LayoutParams.MATCH_PARENT
//        p.height = ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window!!.attributes = p
    }

    private fun bitmapTest() {
        //41990400
        val option = BitmapFactory.Options()
        //10497600
        option.inSampleSize = 2
        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.cat, option)
        Log.e("bitmapTest", "bitmap-->" + bitmap.byteCount)
    }

    //提前初始化一个引擎 跳转时会更刘畅
    private fun initFlutterE() {
        engine = FlutterEngine(this)
        //增加路由条件(没有者直接跳转到main)
//        engine.navigationChannel.setInitialRoute("pagerTow")
        engine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())
        FlutterEngineCache.getInstance().put(FLUTTER_ID, engine)

        //向flutter中发送数据(由flutter中方法触发)
        MethodChannel(engine.dartExecutor, "tts").setMethodCallHandler { call, result ->
            Log.e("MethodChannel", " --- " + call.method)
            when (call.method) {
                "sst" -> {
                    result.success("数据x")
                }
                "showToast" -> {
                    Toast.makeText(this, call.arguments as String, Toast.LENGTH_LONG).show()
                }
                else -> {
                    result.success("数据**")
                }
            }
        }
    }

    override fun onDestroy() {
        engine.destroy()
        super.onDestroy()
    }
}